package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-16 20:31
 **/
public class LeetCode59 {

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        //记录是否遍历完成
        int count = 0;
        //二维数组横坐标
        int i = 0;
        //二维数组纵坐标
        int j = 0;
        //记录数组当前方向需要遍历的次数,第一轮遍历n次，第二轮遍历n-1次，第三轮遍历n-1次，第四轮遍历n-2次
        int k = n;
        while (count < n * n) {
            for (int i1 = 0; i1 < k; i1++) {
                count++;
                matrix[i][j] = count;
                j++;
            }
            j--;
            i++;
            k--;
            for (int i1 = 0; i1 < k; i1++) {
                count++;
                matrix[i][j] = count;
                i++;
            }
            i--;
            j--;
            for (int i1 = 0; i1 < k; i1++) {
                count++;
                matrix[i][j] = count;
                j--;
            }
            j++;
            i--;
            k--;
            for (int i1 = 0; i1 < k; i1++) {
                count++;
                matrix[i][j] = count;
                i--;
            }
            i++;
            j++;
        }
        return matrix;
    }

    public static void main(String[] args) {
        LeetCode59 code = new LeetCode59();
        code.generateMatrix(3);
    }

}
